package org.itboys.mobile.service.mongo.weixin.member;

import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.image.ImageUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.member.SundayMemberDto;
import org.itboys.mobile.dto.member.SundayWeixinMemberDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.wallet.CooWallet;
import org.itboys.mobile.service.mongo.weixin.code.CooValicodeService;
import org.itboys.mobile.service.mysql.weixin.wallet.CooWeixinWalletService;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created on 2017/12/7.
 * @author 朱坤涛
 * dec:会员相关，微信版
 */
@Service
public class SundayWeixinMemberService extends BaseMongoService<SundayMember> {
    @Autowired
    private CooValicodeService valicodeService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private CooWeixinWalletService walletService;

    @Resource(name="weixinDS")
    private MongoDataSource mongoDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mongoDataSource;
    }
    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }
    public void login(Long memberId,String mobile,String code){
        valicodeService.checkValidateCode(mobile,code);
        SundayMember member=super.getById(memberId);
        //如果用户没有手机号   说明是第一次登陆
        if(StringUtils.isBlank(member.getUserName())){
            member.setUserName(mobile);
            super.updateExceptEmpty(memberId,member);

        }else {

            if(!mobile.equals(member.getUserName())){
                throw  new ErrorException("账号错误");
            }
        }


    }
    /**
     * 将用户转换DTO保存到sesssion中。微信专用
     * @param request
     * @param memberId
     * @param memberSessionDto
     */
    public void insertMemberToSession(HttpServletRequest request, Long memberId, SundayWeixinMemberDto memberSessionDto){
        SundayMember member = null;
        if(LongUtil.isNotNull(memberId)){
            member=super.getById(memberId);
            memberSessionDto=new SundayWeixinMemberDto(member.getId(),member.getRecommendId(),member.getIsAble(), member.getWeixinUnionId(), member.getWeixinOpenId());
        }
        logger.info("-----------插入session中的用户信息,openID==="+memberSessionDto.getWeixinOpenId());
        request.getSession().setAttribute("member", memberSessionDto);
    }

    /**
     * 清除用户session
     * @param request
     * @param memberId
     */
    public void clearMemberToSession(HttpServletRequest request, Long memberId){

        Object object=request.getSession().getAttribute("member");
        if(object!=null){
            SundayWeixinMemberDto memberSessionDto=(SundayWeixinMemberDto)object;
            request.getSession().setAttribute("member", object);
        }

    }
    /**
     * 通过weixinopentId查询用户
     * @param openId
     * @return
     */
    public SundayWeixinMemberDto checkOpenId(String openId){
        Map<String,Object> param=new HashMap<String ,Object>();
        param.put("isDeleted",0);
        param.put("weixinOpenId",openId);
        List<SundayMember> members = super.list(param);
        if(ListUtil.isNull(members))return null;
        SundayMember  member = members.get(0);
        return new SundayWeixinMemberDto(member.getId(),member.getRecommendId(),member.getIsAble(), member.getWeixinUnionId(), member.getWeixinOpenId());
    }
    /**
     * 处理来至微信的用户信息。使用unionId判断标识
     * @param unionId
     * @param openId
     * @param nickName
     * @param wxLogo
     */
    public SundayWeixinMemberDto handleMemberInfo(String unionId,
                                                   String openId,
                                                   String nickName,
                                                   String wxLogo,
                                                   Long recommendId){
        SundayMember member=null;
        Map<String,Object> param=new HashMap<String ,Object>();
        param.put("isDeleted",0);
        //使用openId标识用户。公众号
        param.put("weixinOpenId",openId);
        //使用openId标识用户。服务号
        //param.put("weixinUnionId",unionId);
        List<SundayMember> oldMembers=super.list(param);
        if(ListUtil.isNotNull(oldMembers)){
            member=oldMembers.get(0);
            if(LongUtil.isNull(member.getRecommendId())&&LongUtil.isNotZreo(recommendId)){
                member.setRecommendId(recommendId);
                SundayMember tjMember=super.getById(recommendId);
                //继承推荐人的销售（推荐）链 并且加上自己的id
                String salesPath = StringUtils.isNotEmpty(tjMember.getSalesPath())?tjMember.getSalesPath()+"/"+member.getId():String.valueOf(member.getId());
                member.setSalesPath(salesPath);
                //继承推荐人的管理链 并且加上自己的id
                String managerPath = StringUtils.isNotEmpty(tjMember.getManagerPath())?tjMember.getManagerPath()+"/"+member.getId():String.valueOf(member.getId());
                member.setManagerPath(managerPath);
                //增加推荐人的下级推荐链
                String firstPath=StringUtils.isNotEmpty(tjMember.getFirstPath())?
                        tjMember.getFirstPath()+"/"+member.getId():
                        String.valueOf(+member.getId());
                tjMember.setFirstPath(firstPath);
                super.updateExceptEmpty(member.getId(),member);
                super.updateExceptEmpty(tjMember.getId(),tjMember);

                CooWallet wallet =walletService.findByMemberId(member.getId());
                wallet.setSalesId(member.getRecommendId());
                wallet.setManagerId(member.getRecommendId());
                walletService.update(wallet);
            }

        }else {
            member=new SundayMember();
            member.setNickName(nickName);
            member.setWeixinUnionId(unionId);
            member.setWeixinOpenId(openId);
            //保存微信头像
            String random= NumberUtil.generateNumber("COO");
            String savePath = resourceHolder.getStringValue("fileUploadPath")+"/wxlogo/"+random+".jpg";
            ImageUtils.buildImg(savePath,wxLogo);
            //头像半链接
            member.setImage("/wxlogo/"+random+".jpg");
            super.save(member);
            //生成钱包
            CooWallet wallet =walletService.findByMemberId(member.getId());

            //2017年11月4日   志强新增推荐人部分
            if(LongUtil.isNotNull(recommendId)){
                member.setRecommendId(recommendId);
                SundayMember tjMember=super.getById(recommendId);
                //继承推荐人的销售（推荐）链 并且加上自己的id
                String salesPath = StringUtils.isNotEmpty(tjMember.getSalesPath())?tjMember.getSalesPath()+"/"+member.getId():String.valueOf(member.getId());
                member.setSalesPath(salesPath);
                //继承推荐人的管理链 并且加上自己的id
                String managerPath = StringUtils.isNotEmpty(tjMember.getManagerPath())?tjMember.getManagerPath()+"/"+member.getId():String.valueOf(member.getId());
                member.setManagerPath(managerPath);
                //增加推荐人的下级推荐链
                String firstPath=StringUtils.isNotEmpty(tjMember.getFirstPath())?
                        tjMember.getFirstPath()+"/"+member.getId():
                        String.valueOf(member.getId());
                tjMember.setFirstPath(firstPath);
                super.updateExceptEmpty(tjMember.getId(),tjMember);
                super.updateExceptEmpty(member.getId(),member);
                wallet.setSalesId(member.getRecommendId());
                wallet.setManagerId(member.getRecommendId());
                walletService.update(wallet);
            }

        }
        SundayWeixinMemberDto memberDto= new SundayWeixinMemberDto(member.getId(),member.getRecommendId(),member.getIsAble(),member.getWeixinUnionId(),member.getWeixinOpenId());
        logger.info("------处理来至微信请求-返回用户信息--"+memberDto.getId());
        return memberDto;
    }



}
